#! /bin/sh

cleanup () {
  trap - EXIT
  ../src/erlrc-eval erlrcstart$$ 'init:stop ()' >/dev/null 2>/dev/null
  rm -rf flass$$
  rm -rf erlrcstart$$
}

trap cleanup EXIT
set -e

{
ERLRC_ROOT=`pwd`/flass$$
export ERLRC_ROOT

rm -rf flass$$
mkdir -p flass$$/nodes/
mkdir -p flass$$/applications/

erl -name erlrcstart$$ -setcookie flass$$ -noshell -noinput -pa ../src/ -erlrc root_dir \"flass$$\" -eval '
  ok = application:load (erlrc),
  receive after infinity -> ok end
' -s erlang halt &

printf "%s" "flass$$" > flass$$/nodes/erlrcstart$$
printf "%s" "turg" > flass$$/nodes/node_not_started

erl -name erlrcstartfindah$$ -setcookie flass$$ -noshell -noinput -eval "
  [ Host ] = tl (string:tokens (atom_to_list (node ()), \"@\")),
  Other = list_to_atom (atom_to_list (erlrcstart$$) ++ \"@\" ++ Host),
  G = fun (_, 0) -> failed;
          (F, N) -> case net_adm:ping (Other) of pong -> ok; 
                                                 pang -> timer:sleep (50),
                                                         F (F, N - 1)
                    end
      end,
  ok = G (G, 100)" -s erlang halt 

mkdir -p erlrcstart$$/test-0.0.0/ebin
cp erlrctest.app erlrctest.beam erlrcstart$$/test-0.0.0/ebin

set +e
../src/erlrc-start erlrctest 0.0.1 "`pwd`/erlrcstart$$/test-0.0.0" && exit 1
set -e
../src/erlrc-start erlrctest 0.0.0 "`pwd`/erlrcstart$$/test-0.0.0" 
../src/erlrc-start erlrctest 0.0.0 "`pwd`/erlrcstart$$/test-0.0.0" 
set +e
../src/erlrc-start erlrctest 0.0.1 "`pwd`/erlrcstart$$/test-0.0.0" && exit 1
set -e
} > test-start.out

exit 0
